package com.mimo.comet.config;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;

import org.springframework.stereotype.Component;

import com.mimo.common.rpc.proto.LogicSessionProxyGrpc;
import com.mimo.common.rpc.proto.LogicSessionProxyGrpc.LogicSessionProxyBlockingStub;

import io.grpc.netty.shaded.io.netty.util.internal.ThreadLocalRandom;
import net.devh.boot.grpc.client.inject.GrpcClient;

@Component
public class LogicSessionPoolFactory {

  private final List<LogicSessionProxyGrpc.LogicSessionProxyBlockingStub> holder = new ArrayList<>();

  @PostConstruct
  public void init() throws IllegalAccessException {
    Field[] fields = this.getClass().getDeclaredFields();
    for (Field f : fields) {
      f.setAccessible(true);
      if (f.getType() == LogicSessionProxyGrpc.LogicSessionProxyBlockingStub.class) {
        holder.add((LogicSessionProxyBlockingStub) f.get(this));
      }
    }
  }

  @GrpcClient(value = "logic-session-1")
  private LogicSessionProxyGrpc.LogicSessionProxyBlockingStub logicSessionProxyBlockingStub1;

  @GrpcClient(value = "logic-session-2")
  private LogicSessionProxyGrpc.LogicSessionProxyBlockingStub logicSessionProxyBlockingStub2;

  @GrpcClient(value = "logic-session-3")
  private LogicSessionProxyGrpc.LogicSessionProxyBlockingStub logicSessionProxyBlockingStub3;

  @GrpcClient(value = "logic-session-4")
  private LogicSessionProxyGrpc.LogicSessionProxyBlockingStub logicSessionProxyBlockingStub4;

  @GrpcClient(value = "logic-session-5")
  private LogicSessionProxyGrpc.LogicSessionProxyBlockingStub logicSessionProxyBlockingStub5;

  @GrpcClient(value = "logic-session-6")
  private LogicSessionProxyGrpc.LogicSessionProxyBlockingStub logicSessionProxyBlockingStub6;

  @GrpcClient(value = "logic-session-7")
  private LogicSessionProxyGrpc.LogicSessionProxyBlockingStub logicSessionProxyBlockingStub7;

  @GrpcClient(value = "logic-session-8")
  private LogicSessionProxyGrpc.LogicSessionProxyBlockingStub logicSessionProxyBlockingStub8;

  @GrpcClient(value = "logic-session-9")
  private LogicSessionProxyGrpc.LogicSessionProxyBlockingStub logicSessionProxyBlockingStub9;

  @GrpcClient(value = "logic-session-10")
  private LogicSessionProxyGrpc.LogicSessionProxyBlockingStub logicSessionProxyBlockingStub10;

  public LogicSessionProxyGrpc.LogicSessionProxyBlockingStub getLogicSessionStub() {
    return holder.get(ThreadLocalRandom.current().nextInt(holder.size()));
  }

}
